package com.tanhua.server.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.tanhua.model.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 认证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //记录请求的路径
        String requestMethod = request.getMethod();
        log.info("请求了路径: {}:{}",requestMethod, request.getRequestURI());
        if(handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if(null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }


        // 验证token是否有效
        // 没有token 返回false,设置响应状态码401
        String token = request.getHeader("Authorization");

        if(StringUtils.isNotEmpty(token)){
            //2. 取出登录用户信息，存入线程
            //2.1 从redis中取出登录用户信息
            String tokenKey = "TOKEN_" + token;
            String loginUser = redisTemplate.opsForValue().get(tokenKey);
            if (StringUtils.isNotEmpty(loginUser)){
                //2.2 有值  转成user对象，存入线程UserHolder
                User user = JSON.parseObject(loginUser, User.class);
                UserHolder.setUser(user);
                return true;
            }
        }

        //2.3 没值
        //返回 false, 设置响应状态码401
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        return false;
    }

    /**
     * controller发送异常，照样执行
     * 移除线程中的对象
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.remove();
    }
}
